<template>
  <div class="contractManage app-container">
    <div class="content">
      <div class="contentBox">
        <div class="search">
          <el-form
            :inline="true"
            :model="searchFrom"
            class="demo-form-inline"
            id="searchFrom"
          >
            <el-form-item>
              <el-input
                v-model="searchFrom.contractNameOrNum"
                placeholder="请输入合同名称"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="searchFrom.status"
                placeholder="合同状态"
                clearable
              >
                <el-option
                  v-for="item in contract_status"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-tree-select
                placeholder="合同类别"
                v-model="searchFrom.contractType"
                :data="businessAttribute"
                default-expand-all
                :render-after-expand="false"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="searchFrom.contractTimeBegin"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="合同日期起"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="searchFrom.contractTimeEnd"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="合同日期止"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-input
                placeholder="销售人员"
                v-model="sales"
                @click="SaleDialog.isDialog = true"
              ></el-input>
              <SelectDialog
                :dialog-param="SaleDialog"
                @ok="selectSales"
                @close="SaleDialog.isDialog = false"
              />
            </el-form-item>
            <el-form-item>
              <el-tree-select
                v-model="searchFrom.businessCategorize"
                placeholder="业务分类"
                :data="userBusinessTypeOption"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit"
                ><el-icon><Search /></el-icon>查询</el-button
              >
              <el-button type="default" @click="resetSearchFrom"
                ><el-icon><RefreshLeft /></el-icon>重置</el-button
              >
            </el-form-item>
            <el-button
              type="primary"
              text
              @click="drawer = true"
              class="float-right"
              >高级搜索</el-button
            >
          </el-form>
          <div>
            <el-button type="primary" @click="newContract"
              ><el-icon><Plus /></el-icon>新建合同</el-button
            >
            <el-button type="primary" plain @click="editEvent">
              <el-icon><Edit /></el-icon>编辑合同</el-button
            >
            <el-button @click="delEvent" type="primary" plain
              ><el-icon><DeleteFilled /></el-icon>删除合同</el-button
            >
            <el-button @click="exportFile" type="primary" plain
              ><el-icon><Download /></el-icon>导出</el-button
            >
          </div>
        </div>
        <div class="tableBox">
          <el-table
            :data="dataList"
            border
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
            @row-dblclick="goPage"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
            ></el-table-column>
            <el-table-column prop="contractName" label="合同名称">
              <template v-slot="scope">
                <div class="conTitle" :title="scope.row.contractName">
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    :content="scope.row.contractName"
                    placement="top-start"
                  >
                    {{ scope.row.contractName }}
                  </el-tooltip>
                  <!-- <a href="javascript:;" @click="goPage(scope.row.rcId)">{{
                    scope.row.contractName
                  }}</a> -->
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="contractNum"
              label="合同编号"
              align="center"
              width="200"
            />
            <el-table-column prop="partyaName" label="合同甲方" />
            <el-table-column
              prop="businessCategorize"
              label="业务分类"
              width="150"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="contractAttribute"
              label="合同性质"
              width="100"
              align="center"
            >
              <template #default="scoped">
                <div>
                  {{
                    scoped.row.contractAttribute == 1 ? '销售合同' : '采购合同'
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="合同状态"
              align="center"
              width="100"
            >
              <template v-slot="scope">
                <dict-drop
                  :options="contract_status"
                  :value="scope.row.status"
                ></dict-drop>
              </template>
            </el-table-column>
            <el-table-column
              label="合同金额(元)"
              prop="contractSum"
              align="center"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="contractTimeBegin"
              label="合同起始时间"
              align="center"
              width="120"
            />
            <el-table-column
              prop="contractTimeEnd"
              label="合同结束时间"
              align="center"
              width="120"
            />
          </el-table>

          <pagination
            v-show="searchFrom.total > 0"
            :total="searchFrom.total"
            v-model:page="searchFrom.pageNum"
            v-model:limit="searchFrom.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
      <el-drawer
        v-model="drawer"
        :with-header="true"
        :show-close="false"
        size="45%"
        id="drawer"
      >
        <template #header>
          <div>高级搜索</div>
          <el-button
            style="cursor: pointer"
            text
            type="primary"
            @click="handleClose"
          >
            <el-icon><CaretRight /></el-icon>收起
          </el-button>
        </template>
        <div>
          <el-form :inline="true" :model="searchFrom" id="drawerFrom">
            <el-row class="flex-grow">
              <el-form-item label="合同名称或编号">
                <el-input
                  v-model="searchFrom.contractNameOrNum"
                  placeholder="合同名称或编号"
                  clearable
                >
                </el-input>
              </el-form-item>
              <el-form-item label="合同属性">
                <el-tree-select
                  placeholder="合同类别"
                  v-model="searchFrom.contractType"
                  :data="businessAttribute"
                  default-expand-all
                  :render-after-expand="false"
                  clearable
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="合同甲方">
                <el-input
                  v-model="searchFrom.partyaName"
                  placeholder="合同甲方"
                  @click="activatePartya"
                >
                </el-input>
                <ChoiceDialog
                  :dialogParam="dialogParamA"
                  @ok="selectPartya"
                  @close="closeDialogA"
                />
              </el-form-item>
              <el-form-item label="合同状态">
                <el-select
                  v-model="searchFrom.status"
                  placeholder="合同状态"
                  clearable
                >
                  <el-option
                    v-for="item in contract_status"
                    :label="item.label"
                    :value="item.value"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item label="合同乙方">
                <el-input
                  v-model="searchFrom.partybName"
                  placeholder="合同乙方"
                  @click="activatePartyb"
                >
                </el-input>
                <ChoiceDialog
                  :dialogParam="dialogParamB"
                  @ok="selectPartyb"
                  @close="closeDialogB"
                />
              </el-form-item>
              <el-form-item label="归属公司">
                <el-tree-select
                  v-model="searchFrom.companyId"
                  :data="department"
                  :props="props"
                  :height="208"
                  placeholder="选择部门"
                  clearable
                  :disabled="needDisabled"
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="销售人员">
                <el-input
                  placeholder="销售人员"
                  v-model="sales"
                  clearable
                  @click="SaleDialog.isDialog = true"
                ></el-input>
                <SelectDialog
                  :dialog-param="SaleDialog"
                  @ok="selectSales"
                  @close="SaleDialog.isDialog = false"
                />
              </el-form-item>
              <el-form-item label="合同金额">
                <el-select
                  v-model="searchFrom.contractSum"
                  placeholder="合同金额"
                  clearable
                >
                  <el-option
                    v-for="item in project_amount"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="合同时间起">
                <el-date-picker
                  v-model="searchFrom.contractTimeBegin"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="选择日期"
                  clearable
                />
              </el-form-item>
              <el-form-item label="合同时间止">
                <el-date-picker
                  v-model="searchFrom.contractTimeEnd"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="选择日期"
                  clearable
                />
              </el-form-item>
            </el-row>
          </el-form>
          <el-row class="justify-center mt-30px">
            <el-button type="primary" @click="onSubmit"
              ><el-icon><Search /></el-icon>查询</el-button
            >
            <el-button @click="resetSearchFrom"
              ><el-icon><RefreshLeft /></el-icon>重置</el-button
            >
          </el-row>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script setup name="ContractList">
import { reactive, getCurrentInstance, toRefs, onActivated } from 'vue'
import { contract_status, contract_type } from '@/hooks/dict/contract.js'
import { useRouter } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import { project_amount, business_attribute } from '@/hooks/dict/useProject'
import {
  contractInfoList,
  contractInfoDelete
} from '@/api/salesManage/contractManage'
import ChoiceDialog from '@/components/SelectDialog/copy.vue'
import useUserStore from '@/store/modules/user'
import { userBusinessTypeOption } from '@/hooks/dict/order'
const commonStore = useCommonStore()
const userStore = useUserStore()
console.log(userStore.userInfo.orgId, 'userSrore')
const isCreater = ref(null)
const router = useRouter()
const { proxy } = getCurrentInstance()
const props = {
  value: 'id',
  label: 'label',
  children: 'children'
}

// 省公司 查看全部 / 分公司 无法筛选
const needDisabled = computed(() => {
  return userStore.userInfo.orgId != '484'
})
// 销售人员
const sales = ref()
// 公司列表
const companyList = ref()
const data = reactive({
  searchFrom: {
    contractNameOrNum: null, // 名称
    status: null, // 状态
    contractTimeBegin: null, // 合同时间起
    contractTimeEnd: null, // 合同时间止
    salesmanIds: null, // 销售人员
    contractSum: null, // 金额
    businessType: null, //业务属性
    contractType: null, // 合同类别
    partya: null,
    partyaName: null,
    partyb: null,
    partybName: null,
    companyId: userStore.userInfo.orgId,
    pageSize: 10,
    total: 0,
    pageNum: 1
  },
  dataList: [],
  rowNum: 0, // 选中行数
  department: [],
  SaleDialog: {},
  selectId: [], // 选中合同ID
  dialogParamA: {},
  dialogParamB: {},
  businessAttribute: []
})

const {
  searchFrom,
  dataList,
  SaleDialog,
  department,
  dialogParamA,
  dialogParamB,
  businessAttribute
} = toRefs(data)
const drawer = ref(false)
function handleClose() {
  drawer.value = false
}

async function init() {
  await getList()
  const res = await commonStore.getUseTreeData()
  businessAttribute.value = arrayToTree(ref(contract_type).value)
  SaleDialog.value = {
    nodeKey: 'uuid',
    isDialog: false,
    data: [res[0]],
    multiple: false,
    defaultCheckedKeys: [],
    checkStrictly: false,
    title: '人员选择'
  }
  department.value = await commonStore.getCompanyData()
  companyList.value = await commonStore.getCompanyData()
  if (dataList.value.length) {
    isCreater.value = userStore.name === dataList.value[0].createBy ? 'all' : ''
  }
}

async function getList() {
  try {
    // searchFrom.value.total = 0
    const response = await contractInfoList({
      ...searchFrom.value,
      salesmanIds: (searchFrom.value.salesmanIds || '').replace(/U/g, '')
    })
    if (response.code === 200 && response.data) {
      searchFrom.value.total = response.data.total
      dataList.value = response.data.records
    }
  } catch (error) {
    console.log(error)
    // proxy.$modal.msgError(error)
  }
}
function handleSelectionChange(row) {
  data.rowNum = row.length
  data.selectId = row.map(item => item.rcId)
}
function newContract() {
  router.push({
    path: '/sales/contract/newContract',
    query: {}
  })
}
function editEvent() {
  if (!data.rowNum) {
    proxy.$modal.msgWarning('请选择一行数据')
    return
  }
  if (data.rowNum > 1) {
    proxy.$modal.msgWarning('当前功能不可多选行')
    return
  }
  router.push({
    path: '/sales/contract/editContract',
    query: { id: data.selectId[0].toString() }
  })
}
function delEvent() {
  if (!data.rowNum) {
    proxy.$modal.msgWarning('请选择一行数据')
    return
  }
  proxy.$modal
    .confirm('是否确认删除?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      contractInfoDelete(data.selectId).then(res => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess(res.data)
        }
        getList()
      })
    })
}

function exportFile() {
  const val = searchFrom.value.contractType
  if (val === '1' || val === '2') {
    searchFrom.value.contractType = '0010'
    searchFrom.value.businessType = val
  } else {
    searchFrom.value.businessType = null
  }
  let params = `?pageNum=${searchFrom.value.pageNum}&pageSize=${searchFrom.value.pageSize}&`
  if (searchFrom.value.contractNameOrNum) {
    params += `contractNameOrNum=${searchFrom.value.contractNameOrNum}&`
  }
  if (searchFrom.value.contractTimeBegin) {
    params += `contractTimeBeginStr=${searchFrom.value.contractTimeBegin}&`
  }
  if (searchFrom.value.contractTimeEnd) {
    params += `contractTimeEndStr=${searchFrom.value.contractTimeEnd}&`
  }
  if (searchFrom.value.businessType) {
    params += `businessType=${searchFrom.value.businessType}&`
  }
  if (searchFrom.value.contractType) {
    params += `contractType=${searchFrom.value.contractType}&`
  }
  if (data.selectId.length) {
    params += `rcId=${data.selectId.toString()}&`
  }
  if (searchFrom.value.salesmanIds) {
    params += `salesmanIds=${searchFrom.value.salesmanIds.replace(/U/gi, '')}&`
  }
  proxy.download(
    'ord/order/ordregcontract/export' + params,
    {
      // contractNameOrNum: searchFrom.value.contractNameOrNum,
      // contractTimeBegin: searchFrom.value.contractTimeBegin,
      // contractTimeEnd: searchFrom.value.contractTimeEnd,
      // businessType: searchFrom.value.businessType,
      // contractType: searchFrom.value.contractType,
      // pageSize: searchFrom.value.pageSize,
      // pageNum: searchFrom.value.pageNum,
      // rcId: data.selectId.length ? data.selectId.join(',') : ''
    },
    `合同信息_${new Date().getTime()}.xlsx`
  )
}

function goPage(row) {
  router.push({
    path: '/sales/contract/contractDetail',
    query: { id: row.rcId }
  })
}

// 重置查询参数
function resetSearchFrom() {
  searchFrom.value.businessCategorize = null
  searchFrom.value.contractNameOrNum = null // 名称
  searchFrom.value.status = null // 状态
  searchFrom.value.contractTimeBegin = null // 合同时间起
  searchFrom.value.contractTimeEnd = null // 合同时间止
  searchFrom.value.salesmanIds = null // 销售人员
  searchFrom.value.contractSum = null // 金额
  searchFrom.value.businessType = null //业务属性
  searchFrom.value.partya = null
  searchFrom.value.partyb = null
  searchFrom.value.partyaName = null
  searchFrom.value.partybName = null
  searchFrom.value.companyId = userStore.userInfo.orgId
  searchFrom.value.contractType = null
  sales.value = null
  getList()
}
const onSubmit = function () {
  const val = searchFrom.value.contractType
  if (val === '1' || val === '2') {
    searchFrom.value.contractType = '0010'
    searchFrom.value.businessType = val
  } else {
    searchFrom.value.businessType = null
  }
  if (searchFrom.value.salesmanIds) {
    searchFrom.value.salesmanIds = searchFrom.value.salesmanIds.replace(
      /U/gi,
      ''
    )
  }
  getList()
  nextTick(() => {
    searchFrom.value.contractType = val
  })
  if (drawer.value) {
    handleClose()
  }
}

/**
 * @params 页码改变重新请求
 * @params val 页码
 */
function handleCurrentChange(val) {
  searchFrom.value.pageNum = val
  getList()
}
/**
 * @params 改变单页显示数据量
 * @params val 显示条数
 */
function handleSizeChange(val) {
  searchFrom.value.pageSize = val
  getList()
}

/**
 * @params 接受SelectDialog组件返回参数
 */
function selectSales(val) {
  sales.value = val.labelData.join(',')
  SaleDialog.value.isDialog = false
  SaleDialog.value.defaultCheckedKeys = val.defaultCheckedKeys
  searchFrom.value.salesmanIds = val.defaultCheckedKeys.join(',')
}

// 激活dialog--甲方
function activatePartya() {
  dialogParamA.value = {
    type: 'dialogParamA',
    isDialog: true,
    data: [],
    _data: companyList.value,
    multiple: false,
    defaultCheckedKeys: searchFrom.value.partya
      ? [searchFrom.value.partya]
      : [],
    checkStrictly: false,
    title: '合同甲方选择',
    switchRoles: ['外部客户', '内部单位'],
    searchConpany: true,
    setHeight: true
  }
}
// 激活dialog--乙方
function activatePartyb() {
  dialogParamB.value = {
    type: 'dialogParamB',
    isDialog: true,
    data: [],
    _data: companyList.value,
    multiple: false,
    defaultCheckedKeys: searchFrom.value.partyb
      ? [searchFrom.value.partyb]
      : [],
    checkStrictly: false,
    title: '合同甲方选择',
    switchRoles: ['外部客户', '内部单位'],
    searchConpany: true,
    setHeight: true
  }
}

/**
 * @params 接受ChoiceDialog组件返回参数（合同甲方）
 */
function selectPartya(val) {
  searchFrom.value.partyaName = val.labelData[0]
  searchFrom.value.partya = val.defaultCheckedKeys[0]
}

/**
 * @params 接受ChoiceDialog组件返回参数（合同乙方）
 */
function selectPartyb(val) {
  searchFrom.value.partybName = val.labelData[0]
  searchFrom.value.partyb = val.defaultCheckedKeys[0]
}
// 关闭dialog
function closeDialogA() {
  dialogParamA.value.isDialog = false
}
// 关闭dialog
function closeDialogB() {
  dialogParamB.value.isDialog = false
}

// 数组转换树
/**
 * @params arr 输入数组
 * @params result 返回树结构
 * @params nodeKey 树唯一标识
 * @params parentId 父id
 *
 */
function arrayToTree(arr, nodeKey = 'value', parentId = 'parentId') {
  const mapObj = new Map()
  const result = []
  arr.forEach(v => {
    mapObj.set(v.value, v)
  })
  for (const [key, val] of mapObj) {
    if (val.parentId && mapObj.has(val.parentId)) {
      if (!mapObj.get(val.parentId).children) {
        mapObj.get(val.parentId).children = []
      }
      const some = mapObj.get(val.parentId).children.some(v => {
        return v.value === val.value
      })
      if (!some) {
        mapObj.get(val.parentId).children.push(val)
      }
    } else {
      result.push(mapObj.get(key))
    }
  }
  return result
}
init()
</script>

<style lang="scss" scoped>
.contractManage {
  .conTitle {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  overflow-y: auto;
  .content {
    .contentBox {
      .search {
        @apply pb-30px;
      }
      .tableBox {
        .footer {
          width: 100%;
          @apply flex flex-row-reverse my-4;
        }
      }
    }
  }
  .statusTip {
    @apply inline-block mr-5px;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: rgb(25, 190, 107);
  }
  .red-bg {
    background-color: red;
  }
  .yellow-bg {
    background-color: rgb(245, 166, 144);
  }
  #searchFrom {
    :deep .el-input__wrapper {
      // width: 200px;
      @apply w-200px;
    }
    :deep .el-form-item {
      margin-right: 10px;
    }
  }
  #drawerFrom {
    :deep .el-form-item {
      width: 50%;
      margin-right: 0;
      :deep .el-form-item__content {
        width: 150px;
      }
    }
  }
  :deep .el-icon {
    @apply mr-5px;
  }
  :deep .el-form-item__label {
    width: 120px;
  }
}
</style>
